package com.teach.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.teach.R;
import com.teach.entity.RotationChart;
import com.teach.exception.CodeException;
import com.teach.service.FileService;
import com.teach.service.RotationChartService;

import lombok.extern.slf4j.Slf4j;

/**
 * <pre>
 * 轮播图控制器
  *  创建时间：2019年12月27日 上午9:37:41
  *  当前版本：V1.0
 * 
 * </pre>
 * @author hqw
 */

@Controller
@RequestMapping("/")
@Slf4j
public class RotationChartController {
	
	@Autowired
	RotationChartService service;
	
	@Autowired
	FileService fileService;

	@RequestMapping("/rotation-chart.html")
	public String doRotationChart(Model model) {
		List<RotationChart> list = service.listAll();
		model.addAttribute("rtc",list);
		return "rotationChart/index-rotation-chart";
	}
	
	@RequestMapping("/rotation-chart-list.html")
	@ResponseBody
	public List<RotationChart> doRotationChartList() {
		return service.listAll();
	}


	
	@RequestMapping("/rotation-chart-add.do")
	public String doRotationChartAdd() {
		return "rotationChart/rotation-chart-add";
	}
	
	/**
	 * 上传轮播图
	 * @param chart
	 * @param file
	 * @return
	 */
	@RequestMapping("rotation-chart-img.do")
	@ResponseBody
	public R doRotationChartImg(RotationChart chart,MultipartFile file) {
		String url=fileService.save(file, true);
		chart.setImgSrc(url);
		service.add(chart);
		return R.ok();
	}
	
	@RequestMapping("/rotation-img.do")
	@ResponseBody
	public List<RotationChart> doRotationChart2(Model model) {
		return service.listAll();
	}
	
	@RequestMapping("/rotation-modify-{imgId}.do")
	public String doRotationChartModify(Model model,@PathVariable Long imgId) {
		model.addAttribute("modelImg",service.get(imgId));
		log.debug("imgId={}",imgId);
		return"rotationChart/rotation-chart-modify";
	}
	@RequestMapping("/rotation-modify-end.do")
	@ResponseBody
	public R doRotationChartModifyEnd(RotationChart chart,MultipartFile file) {
		log.debug("file={}",file);
		if(file!=null && !file.isEmpty()) {
			chart.setImgSrc(fileService.save(file, true));
		}else {
			chart.setImgSrc(service.get(chart.getImgId()).getImgSrc());
		}
		log.debug("chart={}",chart);
		service.modify(chart);
		return R.ok();
	}
	
	/**
	 * 删除轮播图
	 * @param imgId
	 * @return
	 */
	@RequestMapping("/rotation-delete.do")
	@ResponseBody
	public R doDeleteRotationChart(Model model,Long imgId) {
		try {
			service.delete(imgId);
			log.debug("imgId={}",imgId);
			return R.ok();
		} catch (Exception e) {
			throw new CodeException(5005);
		}
	}

	
}
